<?php

namespace app\controllers;

use Yii;
use app\models\Task;
use app\models\User;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * TaskController implements the CRUD actions for Task model.
 */
class TaskController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Task models.
     * @return mixed
     */
    public function actionIndex()
    {
        $data = Task::find()->select('yearmonth, sum(task_num) as task_num')->groupBy('yearmonth')->orderBy('yearmonth desc')->all();

        return $this->render('index', [
            'data' => $data,
        ]);
    }

    /**
     * Displays a single Task model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView()
    {
        $month = Yii::$app->request->get('month');

        if ($month != null) {
            $list = Task::find()->select('distinct(yearmonth)')->all();

            $month_options = [];
            if (null != $list && count($list) > 0) {
                foreach ($list as $t) {
                    $p_month = date('Y-m', strtotime($t->yearmonth));
                    if ($p_month == $month) {
                        $month_options[] = ['name' => $p_month, 'selected' => true];
                    } else {
                        $month_options[] = ['name' => $p_month, 'selected' => false];
                    }
                }
            }

            $tasks = Task::find()->where("date_format(yearmonth, '%Y-%m') = '{$month}'")->orderBy('id')->all();

            return $this->render('view', [
                'month' => $month,
                'tasks' => $tasks,
                'month_options' => $month_options
            ]);
        }
    }

    /**
     * Creates a new Task model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {

        $month = Yii::$app->request->post('month');
        $task_var_list = Yii::$app->request->post('task');
        if ($month != null && $task_var_list != null && count($task_var_list) > 0) {
            foreach ($task_var_list as $var) {
                $var['task_num'] = (int)$var['task_num'];
                if ($var['task_num'] > 0) {
                    $model = new Task();
                    $model->isNewRecord = true;
                    $model->user_id = $var['user_id'];
                    $model->yearmonth = $month . '-01';
                    $model->task_num = $var['task_num'];
                    $model->createtime = date('Y-m-d H:i:s');
                    $model->lastupdatetime = $model->createtime;
                    if ($model->save()) {
                        //var_dump($model);
                    } else {
                        var_dump($model->errors);
                    }
                    unset($model);
                }
            }
            return $this->redirect(['view', 'month' => $month]);
        }



        $user_array = [];
        $user_list = User::find()->where("status = '在职'")->orderBy('job, id')->all();
        if ($user_list != null && count($user_list) > 0) {
            foreach ($user_list as $u) {
                if ($user_array[$u->jobname] == null) {
                    $user_array[$u->jobname] = [];
                }
                $user_array[$u->jobname][] = ['id' => $u->id, 'name' => $u->showname];
            }
        }

        $last_month_task = Task::find()->orderBy('yearmonth desc')->one();
        if ($last_month_task != null) {
            $next_month = date('Y-m', strtotime("$last_month_task->yearmonth +1 month"));
        } else {
            $next_month = date('Y-m');
        }

        return $this->render('create', [
            'user_array' => $user_array,
            'next_month' => $next_month
        ]);
    }

    /**
     * Updates an existing Task model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate()
    {
        $month = Yii::$app->request->get('month');
        $task_var_list = Yii::$app->request->post('task');
        if ($month != null && $task_var_list != null && count($task_var_list) > 0) {
            foreach ($task_var_list as $var) {
                $var['task_num'] = (int)$var['task_num'];
                if ($var['task_num'] > 0) {
                    $model = new Task();
                    $model->isNewRecord = true;
                    $model->user_id = $var['user_id'];
                    $model->yearmonth = $month . '-01';
                    $model->task_num = $var['task_num'];
                    $model->createtime = date('Y-m-d H:i:s');
                    $model->lastupdatetime = $model->createtime;
                    if ($model->save()) {
                        //var_dump($model);
                    } else {
                        var_dump($model->errors);
                    }
                    unset($model);
                }
            }
            return $this->redirect(['view', 'month' => $month]);
        }


        $task_list = Task::find()->where("date_format(yearmonth, '%Y-%m') = '{$month}'")->orderBy('id')->all();
        $user_array = [];
        if ($task_list != null && count($task_list) > 0) {
            foreach ($task_list as $t) {
                if (null == $user_array[$t->user->jobname]) {
                    $user_array[$t->user->jobname] = [];
                }
                $user_array[$t->user->jobname][] = ['id' => $t->user->id, 'name' => $t->user->showname, 'task_id' => $t->id, 'task_num' => $t->task_num];
            }
        }

        $next_month = Yii::$app->request->get('month');

        return $this->render('update', [
            'user_array' => $user_array,
            'next_month' => $next_month
        ]);
    }

    /**
     * Finds the Task model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Task the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Task::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
